package com.example.test1;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends FragmentActivity 
	implements DiscardDialog.DiscardDialogListener, ErrorDialog.ErrorDialogListener { 
	
	public EditText email;
	public EditText subject;
	public EditText message;

	public static final Pattern email_pattern = 
			Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
	public List<String> errors  = new ArrayList<String>();
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        email = (EditText) findViewById(R.id.email_value);
		subject = (EditText) findViewById(R.id.subject);
		message = (EditText) findViewById(R.id.message);
        
        Button sendButton = (Button)findViewById(R.id.submit);
        Button discardButton = (Button)findViewById(R.id.discard);
        
        sendButton.setOnClickListener(sendListener);
        discardButton.setOnClickListener(discardListener);
    }

    @Override
	public List<String> getErrors() {
		return errors;
	}

	@Override
	public void onDialogCleanClick(DialogFragment dialog) {
		// TODO Auto-generated method stub
		email.setText("");
		subject.setText("");
		message.setText("");
	}
	
	public boolean validate() {
		errors.clear();
		
		String email_str = email.getText().toString();
		String subject_str = subject.getText().toString();
		String message_str = message.getText().toString();
		
		Matcher email_matcher = email_pattern.matcher(email_str);
		
		if (email_str.equals("")) {
			errors.add("Email can not be empty");
		} else if (!email_matcher.find()) {
			errors.add("Email is not correct");
		}
		
		if (subject_str.equals("")) {
			errors.add("Subject can not be empty");
		}
		
		if (message_str.equals("")) {
			errors.add("Message can not be empty");
		}
		return errors.isEmpty();	
	}
	
	private OnClickListener sendListener = new OnClickListener() {
		
		public void onClick(View v) {
			DialogFragment dialog;
	    	
			if (validate()) {
				dialog = new CofirmationDialog();
			} else {
				dialog = new ErrorDialog();
			}
			dialog.show(getSupportFragmentManager(), "CofirmationDialog");
	    }
	};
	
	private OnClickListener discardListener = new OnClickListener() {
		
		public void onClick(View v) {
	      // do something when the button is clicked
	    	DialogFragment dialog = new DiscardDialog();
	    	dialog.show(getSupportFragmentManager(), "DiscardDialog");
	    }
	};
	
}
